package com.moorror.codegenvel.view.window.codegen.view;

import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.components.JBScrollPane;
import com.moorror.codegenvel.db.sqlite.entity.CodeGenTemplate;
import com.moorror.codegenvel.utils.JPanelUtils;
import com.moorror.codegenvel.utils.ProjectUtils;

import javax.swing.*;
import java.awt.*;

/**
 * @Author jiyanghuang
 * @Date 2025/8/15 22:28
 */
public class TabCodeGenTemplateKeyFields extends JPanel {
    private JTextField textFileName;
    private JTextField textSavePath;
    private JPanel rootPanel;
    private JButton buttonSavePath;
    private JCheckBox cbSkipGenCode;
    private JCheckBox cbCoverPrompt;
    private JTextField textFieldRemarks;
    private JTextField tfOrderGen;

    private CodeGenTemplate codeGenTemplate;
    private Project project;

    public TabCodeGenTemplateKeyFields() {

    }

    public TabCodeGenTemplateKeyFields(Project project, CodeGenTemplate codeGenTemplate) {
        this.project = project;
        this.codeGenTemplate = codeGenTemplate;
        setLayout(new BorderLayout());
        add(new JBScrollPane(rootPanel), BorderLayout.CENTER);
        fillPanel();
        initEvent();
    }

    public void fetchFromPanel() {
        JPanelUtils.fillTextToObj(textFileName.getText(), codeGenTemplate::setFileName);
        JPanelUtils.fillTextToObj(textSavePath.getText(), codeGenTemplate::setSavePath);
        JPanelUtils.fillTextToObj(textFieldRemarks.getText(), codeGenTemplate::setDescTemplate);
        JPanelUtils.fillTextToObj(tfOrderGen.getText(), codeGenTemplate::setOrderGen);
        codeGenTemplate.setSkipGenCode(cbSkipGenCode.isSelected());
        codeGenTemplate.setCoverPrompt(cbCoverPrompt.isSelected());
    }

    public void fillPanel() {
        JPanelUtils.fillObjToText(codeGenTemplate::getFileName, textFileName);
        JPanelUtils.fillObjToText(codeGenTemplate::getSavePath, textSavePath);
        JPanelUtils.fillObjToText(codeGenTemplate::getDescTemplate, textFieldRemarks);
        JPanelUtils.fillObjToText(codeGenTemplate::getOrderGen, tfOrderGen);
        cbSkipGenCode.setSelected(codeGenTemplate.isSkipGenCode());
        cbCoverPrompt.setSelected(codeGenTemplate.isCoverPrompt());
    }

    private void initEvent() {
        //选择路径
        buttonSavePath.addActionListener(e -> {
            //将当前选中的model设置为基础路径
            VirtualFile path = ProjectUtils.fetchBaseDir(project);
            VirtualFile virtualFile = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor(), project, path);
            if (virtualFile != null) {
                textSavePath.setText(virtualFile.getPath());
            }
        });
    }
}
